package com.example.service.impl;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.example.dto.PasswordLoginDTO;
import com.example.exception.BaseException;
import com.example.model.api.Result;
import com.example.service.CaptchaService;
import com.example.service.LoginService;
import com.example.validator.ValidatorUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.assertj.core.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * @program: qar-cloud
 * @description:
 * @author: yyyyjinying
 * @create: 2023-10-08 13:42
 **/
@Service
public class LoginServiceImpl implements LoginService {
    @Value("${AES.decryptKey}")
    private String decryptKey;

    @Value("${AES.decryptIv}")
    private String decryptIv;

    @Autowired
    private Environment environment;
    @Autowired
    private RegisteredClientRepository registeredClientRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private CaptchaService captchaService;

    private String decryptPassword(String password) {
//        AES解密
        AES aes = new AES("CBC", "PKCS7Padding",
                // 密钥，可以自定义
                decryptKey.getBytes(),
                // iv加盐，按照实际需求添加
                decryptIv.getBytes());
        return aes.decryptStr(password);
    }

    @Override
    public Result<Map<String, Object>> passwordLogin(PasswordLoginDTO passwordLoginDTO) {
        String uuid = passwordLoginDTO.getUuid();
        String captcha = passwordLoginDTO.getCaptcha();
        boolean flag = captchaService.validate(uuid, captcha);
        if (!flag) {
            throw new BaseException("验证码错误");
        }

//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
//        String authorization = request.getHeader("Authorization");
//        if (Strings.isNullOrEmpty(authorization)) {
//            throw new BaseException("Basic 客户端id密钥不能为空", HttpStatus.UNAUTHORIZED);
//        }
        // 判断是否是正确client
//        String clientInfo = new String(Base64Decoder.decode(authorization.replace("Basic ", "")));
//        String clientId = clientInfo.split(":")[0], clientSecret = clientInfo.split(":")[1];
//        RegisteredClient client = registeredClientRepository.findByClientId(clientId);
//        if (Objects.isNull(client)) {
//            throw new BaseException("客户端信息未在授权服务器注册", HttpStatus.UNAUTHORIZED);
//        }
//        if (!passwordEncoder.matches(clientSecret, client.getClientSecret())) {
//            throw new BaseException("客户端凭证不匹配", HttpStatus.UNAUTHORIZED);
//        }

        HashMap<String, Object> objectHashMap = new HashMap<>();
        objectHashMap.put("grant_type", AuthorizationGrantType.PASSWORD.getValue());
        objectHashMap.put("username", passwordLoginDTO.getUsername());
        // 兼容前端加密
        if (Optional.ofNullable(passwordLoginDTO.getIsNotDecrypt()).orElse(false)) {
            objectHashMap.put("password", passwordLoginDTO.getPassword());
        } else {
            objectHashMap.put("password", decryptPassword(passwordLoginDTO.getPassword()));
        }
        objectHashMap.put("scope", "message.read");
        String body = HttpRequest.post(environment.getProperty("spring.security.oauth2.resourceserver.jwt.issuer-uri") + "/oauth2/token")
                .basicAuth("zy1904807846818746369", "44af39b11e6ff03e303a21ab2c946faf")
//                .basicAuth(clientId, clientSecret)
                .form(objectHashMap)
                .execute().body();
        Map map = JSONUtil.toBean(body, Map.class);
        if (map.containsKey("error")){
            return Result.error(map.get("error").toString());
        }
        return new Result<Map<String, Object>>().ok(JSONUtil.toBean(body, Map.class));
    }
}
